from .car import Car
from .move import MoveList


MAIN_CAR_INDEX = 0


class Problem():
    """
    Takes the dict like:
    {
        "cars": [
            {
                "length": 2,
                "position": {
                    "x": 0,
                    "y": 2
                },
                "allow_direction": "x"
            },
            ...
        ]
    }
    """

    CARS_KEY_NAME = 'cars'

    car_list : list[Car]

    def __init__(self, problem_dict : dict) -> None:
        self.car_list = []

        car_dict_list : list[dict] = problem_dict[self.CARS_KEY_NAME]
        for car_dict in car_dict_list:
            self.car_list.append(Car(car_dict))


    def isWin(self) -> bool:
        main_car = self.car_list[MAIN_CAR_INDEX]

        return main_car.IsWin()


    def IsMovesSolvesProblem(self, move_list : MoveList) -> bool:
        self.car_list[MAIN_CAR_INDEX].is_main_car = True
        for i, move in enumerate(move_list):
            accessing_car = self.car_list[move.car_index]

            if move.move_direction != accessing_car.allow_direction:
                print('move direction not allowed')
                return False

            other_cars = self.car_list[:move.car_index] + self.car_list[move.car_index + 1:]
            try:
                accessing_car.Move(move.diff, other_cars)
            except Exception as e:
                print('cannot move car ', move.car_index, i)
                print(e.args)
                return False

        return self.isWin()


    def IsSolvable(self) -> bool:
        # TODO: The Diy problem phase needs this.
        pass
